﻿using Coolzon.Common;
using Coolzon.Realtime.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coolzon.Realtime.ServerApp.ServiceImplement
{
    public abstract class BaseHandler<TRequestData, TResponseData> : IRequestHandler
    {
        public byte ResponseScenario{get;set;}
        public byte ResponseCommand { get; set; }

        public BaseHandler(byte responseScenario, byte responseCommand)
        {
            ResponseScenario = responseScenario;
            ResponseCommand = responseCommand;
        }

        public Response OnHandle(Request request)
        {
            DateTime startTime = DateTime.Now;
            object objData = SerializeUtility.DeserializeFromBinary(request.Data);
            if (objData == null)
            {
                return null;
            }

            TRequestData requestData = (TRequestData)objData;

            TResponseData responseData = OnHandle(request, requestData);

            Response response = new Response();
            if (responseData != null)
            {
                response.Data = SerializeUtility.SerializeToBinary(responseData);
                long handleTicks = (DateTime.Now - startTime).Ticks;
                ResponseHeader responseHeader = new ResponseHeader();
                responseHeader.Scenario = ResponseScenario;
                responseHeader.Command = ResponseCommand;
                responseHeader.HandleTicks = handleTicks / 10000;
                if (response.Data != null)
                {
                    responseHeader.DataLength = response.Data.Length;
                }
                responseHeader.SendTicks = request.Header.SendTicks / 10000;
                responseHeader.RequestHeader = request.Header;

                response.Header = responseHeader;

                return response;
            }
            else
            {
                return null;
            }
        }

        protected abstract TResponseData OnHandle(Request request, TRequestData requestData);
    }
}
